package utils

import (
	"bufio"
	"io"
	"io/fs"
	"os"
	"regexp"
)

// 定义接口，mockgen根据这个生成对应的mock文件
type LogsView interface {
	ReadFile(filename string) (data []byte, err error)
}

// 读取目录内容，获取文件列表
func ReadDir(dirname string) (files []fs.DirEntry, err error) {
	files, err = os.ReadDir(dirname)
	return
}

// 按行读取文件
func ReadLines(filename string) (lines []string, err error) {
	file, err := os.Open(filename)
	if err != nil {
		return
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	for {
		line, err := reader.ReadString('\n')
		if err != nil || io.EOF == err {
			break
		} else {
			lines = append(lines, line)
		}
	}
	return
}

// 读取整个文件
func ReadFile(filename string) (data []byte, err error) {
	data, err = os.ReadFile(filename)
	return
}

// 从头部读取n行
func ScanLines(filename string, n int64) (lines []string, err error) {
	file, err := os.Open(filename)
	if err != nil {
		return
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	var i int64
	for scanner.Scan() {
		if i == n {
			break
		}
		lines = append(lines, scanner.Text())
		i++
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return
}

// 范围读取[from, to]行
func ScanRangeLines(filename string, from int64, to int64) (lines []string, err error) {
	file, err := os.Open(filename)
	if err != nil {
		return
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	var i int64
	for scanner.Scan() {
		i++
		if i < from {
			continue
		}
		if i > to {
			break
		}
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return
}

// 关键字搜索
func Grep(strs []string, pattern string, caseInsensitive bool) (lines []string, err error) {
	// 大小写不敏感
	if caseInsensitive {
		pattern = "(?i)" + pattern
	}
	reg, err := regexp.Compile(pattern)
	if err != nil {
		return
	}
	for _, line := range strs {
		if reg.MatchString(line) {
			lines = append(lines, line)
		}
	}
	return
}
